package com.jie.client.service.ui.view;

import com.jie.client.core.ClientApplication;
import com.jie.client.core.handler.ClientWriteHandler;
import com.jie.client.service.entity.model.SingleChat;
import com.jie.client.service.entity.model.User;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 单聊视图
 * @author XieZhiJie
 * @date 2022/04/28 16:15
 */
public class SingleChatView {

    /*private final Logger logger = LoggerFactory.getLogger(SingleChatView.class);*/

    /**
     * 当前用户信息
     */
    private final User user;

    /**
     * 聊天对象用户信息
     */
    private final User otherUser;

    /**
     * 正在单聊的用户id集合
     */
    private final Set<Integer> singleChatSet;

    /**
     * 记录消息的TextArea
     */
    private final TextArea singleChatMessage = new TextArea();

    /**
     * 记录要发送的消息
     */
    private final TextArea singleSendMessage = new TextArea();

    /**
     * 初始化单聊信息
     * @param user      当前用户
     * @param otherUser 聊天对象用户
     */
    public SingleChatView(User user, User otherUser, Set<Integer> singleChatSet) {
        this.user = user;
        this.otherUser = otherUser;
        this.singleChatSet = singleChatSet;
    }

    /**
     * 创建单聊视图
     */
    public void createSingleChatView() {
        Stage singleChatStage = new Stage();

        // 顶部的私聊信息
        VBox scBox = new VBox();
        Text scText = new Text();
        Text scSendMsgText = new Text("向对方发送消息");
        // 聊天记录按钮
        Button chatRecordButton = new Button("聊天记录");
        // 发送按钮
        Button scSendMsgButton = new Button("发送消息");

        // 放聊天记录和共享画板功能的Box
        HBox functionBox = new HBox();

        // 设置HBox内控件的间距
        functionBox.setSpacing(20);
        HBox.setMargin(scSendMsgText, new Insets(10 ,0, 0, 0));
        HBox.setMargin(chatRecordButton, new Insets(0, 0, 0, 666));

        // 把scSendMsgText文字和聊天记录功能放入functionBox中
        functionBox.getChildren().add(scSendMsgText);
        functionBox.getChildren().add(chatRecordButton);

        // 设定顶部信息
        scText.setText("\t\t\t\t\t\t\t\t\t\t\t向" + this.otherUser.getUsername() + "("  + this.otherUser.getUserAccount() + ")发起私聊");

        // 消息窗口不可输入
        this.singleChatMessage.setEditable(false);

        // 消息窗口的颜色
        this.singleChatMessage.setStyle("-fx-text-fill: mediumvioletred");

        // 给发送信息按钮添加事件
        scSendMsgButton.setOnAction(event -> onSingleChatSendMessageAction());

        // 给聊天记录按钮添加事件
        chatRecordButton.setOnAction(event -> onChatRecordsAction());

        // 添加控件
        scBox.getChildren().add(scText);
        scBox.getChildren().add(this.singleChatMessage);
        scBox.getChildren().add(functionBox);
        scBox.getChildren().add(this.singleSendMessage);
        scBox.getChildren().add(scSendMsgButton);

        // 把聊天框放入viewMap中给其它线程使用
        ClientApplication.VIEW_MAP.put("singleChatMessage" + this.otherUser.getUserId(), this.singleChatMessage);

        // 设置控件位置
        scBox.setPadding(new Insets(10, 15, 10, 15));
        scBox.setSpacing(20);

        // 设置聊天信息框大小
        this.singleChatMessage.setMinHeight(450);

        // 设置发送消息按钮位置
        VBox.setMargin(scSendMsgButton, new Insets(0 ,0 ,0, 790));

        // 设置场景
        Scene pcScene = new Scene(scBox, 900, 700);
        singleChatStage.setScene(pcScene);
        singleChatStage.setTitle("私聊");
        singleChatStage.show();

        // 当这一个窗口关掉的时候, 删除掉与之私聊的用户
        singleChatStage.setOnCloseRequest(event -> {
            this.singleChatSet.remove(Integer.parseInt(this.otherUser.getUserId()));
            ClientApplication.VIEW_MAP.remove("singleChatMessage" + this.otherUser.getUserId());
        });

    }

    /**
     * 发送信息按钮
     */
    private void onSingleChatSendMessageAction() {
        if ("".equals(this.singleSendMessage.getText())) {
            return;
        }
        // 封装请求
        Map<String, Object> map = new HashMap<>(4);
        map.put("choice", "chatToOne");
        SingleChat singleChat = new SingleChat();
        map.put("singleChat", singleChat);
        singleChat.setSendUserId(Integer.parseInt(this.user.getUserId()));
        singleChat.setReceiveUserId(Integer.parseInt(this.otherUser.getUserId()));
        singleChat.setChatMessage(this.singleSendMessage.getText());
        ClientWriteHandler.sendRequest(map);
        // 更新自己的私聊窗口
        // 是用本地时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        synchronized (this.singleChatMessage) {
            this.singleChatMessage.appendText(
                    "\n" + this.user.getUsername() + "(" + this.user.getUserAccount() + ") " + simpleDateFormat.format(new Date())
                            + " (我)"
                            + "\n" + this.singleSendMessage.getText().trim()
            );
        }
        this.singleSendMessage.clear();
    }

    /**
     * 点击聊天记录事件
     */
    private void onChatRecordsAction() {
        Map<String, Object> map = new HashMap<>(4);
        map.put("choice", "chatToOneRecords");
        map.put("targetUserId", Integer.parseInt(this.otherUser.getUserId()));
        // 创建出窗口后再发送请求
        new ChatRecordView(this.otherUser).createChatRecordView();
        ClientWriteHandler.sendRequest(map);
    }

}
